/**
 * 
 */
package personnal.blog2pdf.writer;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.commons.lang.Validate;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class HtmlEntityResolver implements EntityResolver {
	
	protected static final String HTML_PUBLIC_ID = "-//W3C//DTD XHTML 1.0 Transitional//EN";
	protected static final String HTML_STRICT_PUBLIC_ID = "-//W3C//DTD XHTML 1.0 Scrict//EN";
	protected static final String HTML_LATIN1_PUBLIC_ID = "-//W3C//ENTITIES Latin 1 for XHTML//EN";
	protected static final String HTML_SYMBOL_PUBLIC_ID = "-//W3C//ENTITIES Symbols for XHTML//EN";
	protected static final String HTML_SPECIAL_PUBLIC_ID = "-//W3C//ENTITIES Special for XHTML//EN";

	private static final String HTML_DTD = "xhtml1-transitional.dtd";
	private static final String HTML_STRICT_DTD = "xhtml1-strict.dtd";
	private static final String HTML_LATIN1_DTD = "xhtml-lat1.ent";
	private static final String HTML_SYMBOL_DTD = "xhtml-symbol.ent";
	private static final String HTML_SPECIAL_DTD = "xhtml-special.ent";

	private final HashMap<String, String> dtdMapById = new HashMap<String, String>();
	
	public HtmlEntityResolver() {
		dtdMapById.put(HTML_PUBLIC_ID, HTML_DTD);
		dtdMapById.put(HTML_STRICT_PUBLIC_ID, HTML_STRICT_DTD);
		dtdMapById.put(HTML_LATIN1_PUBLIC_ID, HTML_LATIN1_DTD);
		dtdMapById.put(HTML_SYMBOL_PUBLIC_ID, HTML_SYMBOL_DTD);
		dtdMapById.put(HTML_SPECIAL_PUBLIC_ID, HTML_SPECIAL_DTD);
	}
	
	public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
		Validate.notEmpty(publicId, "Parameter 'publicId' is empty");
		if (dtdMapById.containsKey(publicId)) {
			InputStream resourceAsStream = getResource(dtdMapById.get(publicId));
			if (resourceAsStream != null) {
				return new InputSource(resourceAsStream);
			}
		}
		throw new IllegalArgumentException("Unrecognized publicId: "+publicId);
	}

	private InputStream getResource(String dtdFile) {
		ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
		InputStream resourceAsStream = contextClassLoader
				.getResourceAsStream(dtdFile);
		return resourceAsStream;
	}
}